package com.isky.visual.db.factory;

import com.isky.visual.constant.CommonConstant;
import com.isky.visual.constant.DbConstant;
import com.isky.visual.db.domain.DatabaseConfig;
import com.isky.visual.db.entity.Source;
import com.isky.visual.exception.GlobalException;
import com.isky.visual.result.CodeMsg;
import com.isky.visual.util.DBUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

/**
 * @version v1.0
 * @ProjectName visual_parent
 * @ClassName MySqlManager
 * @Description mysql 的相关管理操作
 * @Author wudl
 * @Date DATE{TIME}
 */
public class MySqlManager implements IDbManager {
    private Logger log = LoggerFactory.getLogger(MySqlManager.class);

    public static final String  SHOW_COLUMN_SQL = "SELECT COLUMN_NAME AS NAME,IF(IFNull(COLUMN_COMMENT,'')='',COLUMN_NAME,COLUMN_COMMENT) AS namecn FROM information_schema.COLUMNS WHERE TABLE_NAME= '%s' AND TABLE_SCHEMA = '%s' ";
    public static final String  SHOW_TABLE_SQL = "SELECT TABLE_NAME,TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA= '%s'";

    private Source source;

    public MySqlManager(Source source) {
        this.source = source;
    }

    @Override
    public Connection getConnection() {
        Connection connection = null;
        try {
            source.setDbType(DbConstant.MYSQL);
            connection = DBUtil.getConnection(source);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据库获取连接异常" + e.getMessage());
            throw new GlobalException(CodeMsg.DB_CONNECTION_ERROR);
        }
        return connection;
    }

    @Override
    public String getShowColumnSql(String tableName,Source source) {
        return String.format(MySqlManager.SHOW_COLUMN_SQL,tableName,source.getDbName());
                //MySqlManager.SHOW_COLUMN_SQL + CommonConstant.DIAN + tableName + CommonConstant.DIAN;
    }

    @Override
    public String getShowTableSql() {
        String sql = "SELECT * from information_schema.TABLES where TABLE_SCHEMA = ?";
        return sql;
    }

    @Override
    public String getShowTableSql(Source source) {
        return  String.format(MySqlManager.SHOW_TABLE_SQL,source.getDbName());
                //MySqlManager.SHOW_TABLE_SQL+ CommonConstant.DIAN + source.getDbName()  + CommonConstant.DIAN;
    }

    /**
     * 获取表字段
     * @param con
     * @param sql
     * @return
     */
    @Override
    public List<Map<String, Object>> getTableColumn(Connection con, String sql) throws Exception {
        return DBUtil.query(con, sql);
    }

    @Override
    public String getSingleTableCountSql(String tableName) {
        return "select count(*) as COUNT  from "+ tableName;
    }

    @Override
    public String getSingleTableDataSql(String tableName, Integer limit) {
        return "select *  from " + tableName + " limit " + limit;
    }


}
